import { ApiCode, ApiResult } from '@/config/api_config/apis_class'
import { Method } from 'axios'
import { getRequest, RequestApiEnum } from '@/config/api_config/request_config/request'

// 请求的后端地址的枚举
export const enum RequestUrlEnum {
  mobileLogin = 'account/login'
}
/**
 * 统一的请求方法
 * @param urlName 请求地址，只支持enum
 * @param config { data: any, params: any, method: Method } 参数配置
 * @return Promise<ApiResult<T>>
 */
function apiSend<T> (urlName: RequestUrlEnum, config: { data?: any, params?: any, method: Method, apiEnum: RequestApiEnum }) : Promise<ApiResult<T>> {
  return new Promise((resolve, reject) => {
    const request = getRequest(config.apiEnum)
    const req = getRequest(config.apiEnum)({
      method: config.method,
      url: urlName.toString(),
      data: config.data,
      params: config.params
    })
    req.then(res => {
      if ((res.headers['content-type']).includes('application/json')) {
        const data = res.data as ApiResult<T>
        if (data.apiCode === ApiCode.Success) {
          resolve(data)
        } else {
          resolve(data)
        }
      }
      resolve(res.data as ApiResult<T>)
    }).catch(reason => {
      reject(reason)
    })
  })
}

/**
 * 手机登录接口
 */
function windMobileLogin () {
  return apiSend(RequestUrlEnum.mobileLogin, { method: 'POST', apiEnum: RequestApiEnum.MobileEnum })
}

export const apiMethod = {
  windMobileLogin
}
